package com.yijiue.ace.core.task;


import com.yijiue.ace.core.InMemoryAce;
import com.yijiue.ace.core.model.AceGray;
import com.yijiue.ace.service.AceGrayService;
import com.yijiue.ace.service.AceRouteDefineService;

import java.util.Map;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 更新灰度配置以及路由定义内存数据
 * @author YIJIUE
 */
public class RefreshConfigTask {

    private static ScheduledExecutorService grayExecutor = new ScheduledThreadPoolExecutor(1, (Runnable r) -> new Thread(r, "gray_thread_pool"));
    private static ScheduledExecutorService routeExecutor = new ScheduledThreadPoolExecutor(1, (Runnable r) -> new Thread(r, "route_thread_pool"));

    private static AceGrayService aceGrayService;
    private static AceRouteDefineService aceRouteDefineService;

    public RefreshConfigTask(AceGrayService aceGrayService, AceRouteDefineService aceRouteDefineService) {
        this.aceGrayService = aceGrayService;
        this.aceRouteDefineService = aceRouteDefineService;
    }

    public void start(){
        grayExecutor.scheduleWithFixedDelay(() -> InMemoryAce.aceGrayMap = aceGrayService.findAceGrayList().stream().collect(Collectors.toMap(AceGray::getRoutingId, Function.identity(), (key1, key2) -> key2))
        , 0 , 5, TimeUnit.SECONDS);

        routeExecutor.scheduleWithFixedDelay(() -> InMemoryAce.aceRouteDefineList = aceRouteDefineService.findAceRouteDefineList()
        , 0 , 5, TimeUnit.SECONDS);
    }

}
